package imaa.framework.persistence;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public abstract class EntityRepository<T extends Entidade> {
	
	@PersistenceContext
	private EntityManager manager;
 
    @SuppressWarnings("unchecked")
	public T findById(Long id) {
        return (T) manager.find(getTypeClass(), id);
    }
 
    public T save(T entity) {
    	if (entity.getId() == null)
    		manager.persist(entity);
    	else
    		manager.merge(entity);
    	return entity;
    }
 
    public void delete(T entity) {
        manager.remove(entity);
    }
 
    @SuppressWarnings("unchecked")
	public List<T> findAll() {
        return manager.createQuery(("FROM " + getTypeClass().getName()))
                .getResultList();
    }
 
    private Class<?> getTypeClass() {
        Class<?> clazz = (Class<?>) ((ParameterizedType) this.getClass()
                .getGenericSuperclass()).getActualTypeArguments()[1];
        return clazz;
    }
}
